package com.leo.blog.util;

import java.util.*;

/**
 * @Classname TreeUtils
 * @Description TODO
 * @Date 2023/4/14 11:40
 * @Created by XiongXiong
 * @Author: X.I.O
 */
public class TreeUtils {

    /**
     * 树的工具类
     * @param id       主键id
     * @param pid      父主键id
     * @param child    子字段
     * @param obj      数据列表
     * @return
     */
    public static List<Map<String,Object>> listToTree(String id, String pid, String child, List<Map<String,Object>> obj){
        if(obj==null){
            return Collections.emptyList();
        }
        //先找出最顶层的
        List<Map<String,Object>> mapLists=new ArrayList<>();
        for (Map<String,Object> map: obj ) {
            Object parentValue=map.get(pid);
            boolean flag=true;
            for (Map<String,Object> mapList: obj ) {
                Object childValue=mapList.get(id);
                if(Objects.equals(parentValue,childValue)){
                    flag=false;
                }
            }
            if(flag){
                mapLists.add(map);
            }
        }
        List<Map<String,Object>> parents=new ArrayList<>();
        //遍历父
        for (Map<String,Object> map: mapLists ) {
            List<Map<String,Object>> mapList=childListToTree(id,pid,child,map,obj);
            map.put(child,mapList);
            parents.add(map);
        }
        return parents;
    }



    private static List<Map<String,Object>> childListToTree(String id,String pid,String child,Map<String,Object> obj,List<Map<String,Object>> mapList){
        if(mapList==null){
            return Collections.emptyList();
        }
        Object parentValue=obj.get(id);
        List<Map<String,Object>> childList=new ArrayList<>();
        for (Map<String, Object> map : mapList) {
            Object childValue=map.get(pid);
            if(Objects.equals(parentValue,childValue)){
                List<Map<String,Object>> list=childListToTree(id,pid,child,map,mapList);
                map.put(child,list);
                childList.add(map);
            }
        }
        return childList;
    }

}
